﻿#region << 文 件 说 明 >>

/*----------------------------------------------------------------
// 文件名称：EntityExtension
// 创 建 者：杨程
// 创建时间：2021/9/17 9:45:22
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//
//
//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Core.Extensions;

/// <summary>
/// 实体类扩展
/// </summary>
public static class EntityExtension
{
    /// <summary>
    /// 简单映射
    /// </summary>
    /// <typeparam name="TTarget">目标类型</typeparam>
    /// <param name="source"></param>
    /// <returns></returns>
    public static TTarget SimpleMap<TTarget>(this object source)
    {
        var result = Activator.CreateInstance(typeof(TTarget));

        var SourceProps = source.GetType().GetProperties();
        var TargetProps = typeof(TTarget).GetProperties();

        foreach (var prop1 in SourceProps)
        {
            foreach (var prop2 in TargetProps)
            {
                if (prop2.PropertyType.IsValueType || prop2.PropertyType.Name.StartsWith("String"))
                {
                    if (prop1.Name == prop2.Name)
                    {
                        try
                        {
                            object value = prop1.GetValue(source, null);
                            var prop = typeof(TTarget).GetProperty(prop1.Name);
                            if (prop != null && prop.CanWrite && value is not DBNull)
                            {
                                prop.SetValue(result, value, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
            }
        }

        return (TTarget)result;
    }
}